package com.yuxinmuyu.sports_management.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yuxinmuyu.sports_management.exception.BusinessException;

import java.util.Date;
import java.util.UUID;

public class JWTUtils {

    //登录生成token中秘钥
    public static final String JWT_TOKEN_PRIVATE_KEY = "yuxinmuyu";


    public static final String JWT_TOKEN_AUTHOR = "zqx";


    /**
     * 生成token令牌
     * @param id 用户id
     * @return token令牌
     */
    public static String getToken(String id,Integer expireSeconds){
        try {
            Algorithm algorithm = Algorithm.HMAC256(JWT_TOKEN_PRIVATE_KEY);
            if(expireSeconds > 0){
                Date expiration = new Date(System.currentTimeMillis() + expireSeconds*1000);
                return JWT.create()
                        .withIssuer(JWT_TOKEN_AUTHOR)
                        .withSubject(id)
                        .withClaim("dynamicFactor", UUID.randomUUID().toString())
                        .withIssuedAt(new Date())
                        .withExpiresAt(expiration)
                        .sign(algorithm);
            }else{
                return JWT.create()
                        .withIssuer(JWT_TOKEN_AUTHOR)
                        .withClaim("dynamicFactor", UUID.randomUUID().toString())
                        .withSubject(id)
                        .withIssuedAt(new Date())
                        .sign(algorithm);
            }
        } catch (Exception e) {
            throw new BusinessException("Token生成时加密异常");
        }
    }


    /**
     *
     * @param token token令牌
     * @return 用户id
     */
    public static String getUserId(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(JWT_TOKEN_PRIVATE_KEY);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(JWT_TOKEN_AUTHOR)
                    .build();
            DecodedJWT decodedJWT = verifier.verify(token);
            return decodedJWT.getSubject();
        }  catch (Exception e) {
            if (e instanceof TokenExpiredException) {
                throw new BusinessException("token已过期");
            }else{
                throw new BusinessException("token已失效");
            }
        }
    }
}
